package com.eden.illness.handler;

import com.eden.illness.service.DataService;
import com.eden.illness.utils.HttpURLConnectionUtil;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DateHandler {
    @Autowired
    private DataService dataService;

    public static String urlStr = "https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5";

    public static void main(String[] args) {
        getData();
    }


    public void saveData() {
        List<SysIllness> illnesses = getData();
        // 先将数据清空  然后存储数据
        dataService.remove(null);
        dataService.saveBatch(illnesses);
    }

    // 配置定时执行的注解  支持cron表达式
    @Scheduled(cron = "0 */30 * * * ?") //每30分钟执行一次
    public void updateData() {
        System.out.println("更新数据");
        saveData();
    }

    public static List<SysIllness> getData() {

        // 分析json字符串对数据进行筛选和提取
        // 实时获取数据
        String respJson = HttpURLConnectionUtil.doGet(urlStr);

        Map<?,?> map = new Gson().fromJson(respJson, Map.class);

        // 此时增加了一层处理  而且data对应的数据格式是string
        String subStr = (String) map.get("data");
        Map<?,?> subMap = new Gson().fromJson(subStr, Map.class);

        // System.out.println(map);

        ArrayList<?> areaList = (ArrayList<?>) subMap.get("areaTree");
        Map<?,?> dataMap = (Map<?,?>) areaList.get(0);
        ArrayList<?> childrenList = (ArrayList<?>) dataMap.get("children");

        // 遍历然后转化
        List<SysIllness> result = new ArrayList<>();

        for (Object o : childrenList) {
            Map<?,?> tmp = (Map<?,?>) o;
            String name = (String) tmp.get("name");

            Map<?,?> totalMap = (Map<?,?>) tmp.get("total");
            double nowConfirm = (Double) totalMap.get("nowConfirm");
            double confirm = (Double) totalMap.get("confirm");
            double heal = (Double) totalMap.get("heal");
            double dead = (Double) totalMap.get("dead");

            SysIllness illness = new SysIllness(name, (int) nowConfirm, (int) confirm,
                    (int) heal, (int) dead);

            result.add(illness);
        }

        return result;
    }
}
